import { useEffect, useState } from "react";

import {
  XHR_PENDING,
  XHR_REJECTED,
  XHR_FULFILLED,
  XHR_IDLE,
} from "./../config/api/xhrStatuses";

const DELAY_MS = 200;

export function useStatusListener(
  _status: string,
  onSuccess?: () => void,
  onReject?: () => void,
  delay?: number
) {
  const [listen, setListen] = useState(false);
  const [status, setStatus] = useState("");

  function delayedResponse(func: () => void) {
    let to: NodeJS.Timeout;
    let delayTime;
    if (delay) {
      delayTime = delay;
      if (typeof delay === "boolean") delayTime = DELAY_MS;
      to = setTimeout(func, delayTime);
      return () => clearTimeout(to);
    }
    return func();
  }
  // console.log(status);
  useEffect(() => {
    if (_status === XHR_PENDING || _status === XHR_IDLE) {
      setListen(true);
      setStatus(_status);
    } else if (listen) {
      setListen(false);
      if (_status === XHR_FULFILLED) {
        console.log("<<<<");
        setStatus(_status);
        if (onSuccess) {
          delayedResponse(onSuccess);
        }
      } else if (_status === XHR_REJECTED) {
        setStatus(_status);
        if (onReject) {
          delayedResponse(onReject);
        }
      }
    } else {
      setStatus(XHR_IDLE);
    }
  }, [_status]);

  const isLoading = status === XHR_PENDING;
  const isFulfilled = status === XHR_FULFILLED;
  const isRejected = status === XHR_REJECTED;

  return {
    status,
    isLoading,
    isFulfilled,
    isRejected,
  };
}
